package com.rpc.center.discover.client.netty;

import com.rpc.center.discover.client.manager.ServerAddressManager;
import com.rpc.common.entity.response.*;
import com.rpc.common.entity.HostInfoPair;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.Getter;
import lombok.Setter;

import java.util.List;
import java.util.concurrent.CountDownLatch;

public class NettyDiscoverServiceHandler extends SimpleChannelInboundHandler<ResponsePackage> {
    private NettyDiscoverServiceImpl discoverService;
    private ServerAddressManager addressManager;
    @Setter
    private CountDownLatch latch;
    @Getter
    private List<HostInfoPair> discoverAddressResult;

    public NettyDiscoverServiceHandler(NettyDiscoverServiceImpl discoverService) {
        this.addressManager = ServerAddressManager.getAddressManagerInstance();
        this.discoverService=discoverService;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        //discoverService.setChannel(ctx.channel());
        System.out.println("连接服务注册中心成功");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ResponsePackage response) throws Exception {
        System.out.println(
                "------------------------Client received message-------------------------");
        ResponseType type=response.getResponseType();
        if(type==ResponseType.DISCOVER_RESPONSE){
            doDiscover((DiscoverRS)response);
        }else if(type==ResponseType.PUBLISHER_ONLINE){
            doPublisherOnline((PublisherOnlineRS)response);
        }else if(type==ResponseType.PUBLISHER_OFFLINE){
            doPubliherOffline((PublisherOfflineRS)response);
        }

    }

    /**
     * 使用闭锁，使服务查询变成同步方法
     * @param discoverRS
     */
    private void doDiscover(DiscoverRS discoverRS){
        System.out.println(discoverRS.getMsg());
        List<HostInfoPair> addressList=discoverRS.getServerAddressList();
        //addressManager.addAvaliableServerList(addressList);
        discoverAddressResult =addressList;
        if(latch!=null){
            latch.countDown();
            latch=null;
        }
    }

    /**
     * 新服务发布方上线
     * @param reponse
     */
    private void doPublisherOnline(PublisherOnlineRS reponse){
        addressManager.addAvaliableServer(reponse.getAddress(),reponse.getPort());
    }

    /**
     * 有服务发布方下线
     * @param offlineRS
     */
    private void doPubliherOffline(PublisherOfflineRS offlineRS){
        addressManager.removePublisher(offlineRS.getAddress());
    }
}
